package com.huiminpay.merchant.common.intercept;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse restErrorResponse(HttpServletRequest request, HttpServletResponse response,Exception e){
        //判断异常捕获的类型是否为自定义异常 如果是的话就进行自定义异常显示错误信息，否则 返回未知错误
        if(e instanceof BusinessException){
            //是 进行强转
           BusinessException businessException =  (BusinessException) e;
           //取出错误码
            ErrorCode errorCode = businessException.getErrorCode();
            int code = errorCode.getCode();
            //取出错误消息
            String desc = errorCode.getDesc();
            return new RestErrorResponse(String.valueOf(code), desc);
        }
        //否则 返回"9999"的未知错误 使用自己定义的状态码
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKNOWN.getCode()),
                CommonErrorCode.UNKNOWN.getDesc());
    }
}
